package com.scpii.api.controller.user;

import java.util.HashMap;

import javax.annotation.Resource;

import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;

import com.scpii.api.common.auth.AuthorizationRequest;
import com.scpii.api.common.auth.AuthorizationRequestManager;
import com.scpii.api.common.auth.client.ClientDetailsService;
import com.scpii.api.common.auth.token.AuthAccessToken;
import com.scpii.api.common.auth.token.TokenGranter;
import com.scpii.api.common.base.BaseController;
import com.scpii.api.domain.auth.UsersInfoDetails;
import com.scpii.api.domain.user.Users;
import com.scpii.api.service.user.UsersService;
import com.scpii.api.util.PrincipalUtil;

@Controller
@RequestMapping("/user/password")
public class PasswordController extends BaseController {

	@Resource
	private UsersService usersService;

	@Resource(name = "defaultClientDetailsService")
	private ClientDetailsService clientDetailsService;

	@Resource(name = "compositeTokenGranter")
	private TokenGranter tokenGranter;

	@Resource(name = "defaultAuthorizationRequestManager")
	private AuthorizationRequestManager authorizationRequestManager;

	@PreAuthorize("hasRole('ROLE_CLIENT')")
	@RequestMapping(method = RequestMethod.PUT)
	@ResponseBody
	public AuthAccessToken setPassword(
			@RequestParam("username") String username,
			@RequestParam("validCode") String validCode,
			@RequestParam("password") String password) {
		Users users = usersService.updatePasswordByValidCodeAndUserName(
				validCode, username, password);
		UsersInfoDetails usersInfoDetails = PrincipalUtil
				.getPrincipal();
		String deviceId = clientDetailsService.loadDevicesByPrimaryKey(
				usersInfoDetails.getDeviceId()).getDeviceId();
		HashMap<String, String> request = new HashMap<String, String>();
		request.put("username", users.getUserName());
		request.put("password", password);
		request.put("appId", String.valueOf(usersInfoDetails.getAppId()));
		request.put("deviceId", deviceId);
		AuthorizationRequest authorizationRequest = authorizationRequestManager
				.createAuthorizationRequest(request);
		AuthAccessToken token = tokenGranter.grant("password",
				authorizationRequest);
		return token;
	}
}
